package com.wb.controller;

import java.awt.Image;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.ImageIcon;

import com.wb.entity.User;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

//可随意更改，usercontroller是一开始用来实践新技术的类
@Controller
public class UserController {

    @RequestMapping(value="/signup")
    public String signup(@RequestParam(value = "picFile",required = false) MultipartFile file,
                         @RequestParam(value = "nickname",required = false) String username,
                         HttpServletRequest request){
        if(file==null)
            return "try";
//      获取Servlet的运行路径下的imgs文件夹作为上传图片的存储路径
        String uploadRootPath = request.getServletContext().getRealPath("imgs/");
        System.out.println("uploadRootPath="+uploadRootPath);

//      检查图片存储路径是否存在，如果不存在，创建路径
        File uploadRootDir = new File(uploadRootPath);
        if(!uploadRootDir.exists())
            uploadRootDir.mkdirs();

//      获取源文件的文件名
        String fileName = file.getOriginalFilename();

//      创建目标文件，制定文件存储路径和文件名
        File targetFile = new File(uploadRootPath+ fileName);

        if(fileName!=null&&fileName.length()>0){
            try {
//              将源文件转移到目标文件，使用transferTo方法
                file.transferTo(targetFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

//      由于获取到的User对象没有userPic属性，这里补全
        System.out.println(username+"fileDir="+uploadRootPath+fileName);
/*
//      实现signUp方法，将用户信息持久化到数据库
        if(userService.signUp(u)){
//          直接将图片路径（这里是文件名）传递给login-success页面
            model.addAttribute("picpath",u.getUserPic());
            return "signup-success";
        }*/
        return "index";
    }

}